<?php
// Module Body

function tomcat_sys(&$data) {
	global $cfg, $restarttomcat;
}

function tomcat_generate_host_conf(&$data) {
	global $cfg;
	unset($search);
	unset($replace);

	// Generate Apache configuration
	// open virthost.tpl
	$file = $cfg['basedir']."/tomcat/templates/host.tomcat.tpl";
	$hostconf = stripslashes(file_get_contents($file));

	// Replace variables by values
	switch($data['type']) {
		case 'domain':
		case 'pointer':
			$domain = $data['domain1'];
			break;
		case 'subdomain':
			$domain = $data['host'].'.'.$data['domain1'];
			break;
	}
	$search[] = "{DOMAIN}";
	$replace[] = $domain;

	$search[] = "{HOST.DOMAIN}";
	$replace[] = $data['host'].".".$data['domain'];

	// set the correct path
	if ($data['type'] == "pointer") {
		$path = $data['path'];
	} else {
		$path = $data['path']."/".$data['host']."/".$cfg['webname'];
	}
	$search[] = "{PATH}";
	$replace[] = $path;

	// Set correct error logs
	if ($data['type'] == 'pointer') {
		$ownerdata = fetchdata("id,host","domain",$data['owner']);
		$log = $cfg['webdir']."/".$ownerdata['id']."/".$ownerdata['host']."/logs";
	}
	else {
		$log = $cfg['webdir']."/".$data['id']."/".$data['host']."/logs";
	}
	$search[] = "{LOGPATH}";
	$replace[] = $log;

	$search[] = "{ALIASES}";
	if ($data['aliases']) {
		$tmp = explode(" ",$data['aliases']);
		while (current($tmp)) {
			$aliaslist .= "<Alias>".current($tmp).".".$data['domain']."</Alias>";
			next($tmp);
		}
		$replace[] = $aliaslist;
	} else {
		$replace[] = "";
	}

	$search[] = "{TOMCATPATH}";
	$replace[] = $cfg['tomcatpath'];

	$hostconf = str_replace($search, $replace, $hostconf);

	return $hostconf;
}

function tomcat_remove_host_conf(&$data) {
	global $cfg;
	unset($search);
	unset($replace);

	// Generate Apache configuration
	// open virthost.tpl
	$file = $cfg['basedir']."/tomcat/templates/host.tomcat.tpl";
	$hostconf = stripslashes(file_get_contents($file));

	// Replace variables by values
	switch($data['type']) {
		case 'domain':
		case 'pointer':
			$domain = $data['domain1'];
			break;
		case 'subdomain':
			$domain = $data['host'].'.'.$data['domain1'];
			break;
	}
	$search[] = "{DOMAIN}";
	$replace[] = $domain;

	$search[] = "{HOST.DOMAIN}";
	$replace[] = $data['host'].".".$data['domain1'];

	// set the correct path
	if ($data['type'] == "pointer") {
		$path = $data['path'];
	} else {
		$path = $data['path']."/".$data['host']."/".$cfg['webname'];
	}
	$search[] = "{PATH}";
	$replace[] = $path;

	// Set correct error logs
	if ($data['type'] == 'pointer') {
		$ownerdata = fetchdata("id,host","domain",$data['owner']);
		$log = $cfg['webdir']."/".$ownerdata['id']."/".$ownerdata['host']."/logs";
	}
	else {
		$log = $cfg['webdir']."/".$data['id']."/".$data['host']."/logs";
	}
	$search[] = "{LOGPATH}";
	$replace[] = $log;

	$search[] = "{ALIASES}";
	if ($data['aliases']) {
		$tmp = explode(" ",$data['aliases']);
		while (current($tmp)) {
			$aliaslist .= "<Alias>".current($tmp).".".$data['domain']."</Alias>";
			next($tmp);
		}
		$replace[] = $aliaslist;
	} else {
		$replace[] = "";
	}

	$search[] = "{TOMCATPATH}";
	$replace[] = $cfg['tomcatpath'];

	$hostconf = trim(str_replace($search, $replace, $hostconf));

	$hostconfarray = explode("\n", $hostconf);
	print_r($hostconfarray);

	$file = $cfg['tomcatpath'].'/conf/server.xml';
	$tomcatconf = file_get_contents($file);

	$start = strpos($tomcatconf, $hostconfarray[0]);
	$end = strpos($tomcatconf, $hostconfarray[sizeOf($hostconfarray)-1], $start) - strlen($tomcatconf) + strlen($hostconfarray[sizeOf($hostconfarray)-1]);

	if ($start && $end) {
		$tomcatconf_stripped = substr($tomcatconf, 0, $start);
		$tomcatconf_stripped .= substr($tomcatconf, $end);
		file_put_contents($file, $tomcatconf_stripped);
		return true;
	} else {
		return false;
	}
}

function  tomcat_domain_create(&$data) {
	global $cfg;
	if ($data['serverside']['jsp'] == 'on') {
		$file = $cfg['tomcatpath'].'/conf/server.xml';
		$tomcatconf = file_get_contents($file);

		$hostconf = tomcat_generate_host_conf($data);

		$tomcatarray = explode('<!-- VIRTUAL HOST INJECTION POINT -->', $tomcatconf);
		$tomcatconf = $tomcatarray[0]."<!-- VIRTUAL HOST INJECTION POINT -->\n".$hostconf.trim($tomcatarray[1]);

		file_put_contents($file, $tomcatconf);
		tomcat_restart();
	}
}

function tomcat_domain_update(&$data) {
	global $cfg;
	$removed = tomcat_remove_host_conf($data);
	if ($data['serverside']['jsp'] == 'on') {
		$file = $cfg['tomcatpath'].'/conf/server.xml';
		$tomcatconf = file_get_contents($file);

		$hostconf = tomcat_generate_host_conf($data);

		$tomcatarray = explode('<!-- VIRTUAL HOST INJECTION POINT -->', $tomcatconf);
		$tomcatconf = $tomcatarray[0]."<!-- VIRTUAL HOST INJECTION POINT -->\n".$hostconf.trim($tomcatarray[1]);

		file_put_contents($file, $tomcatconf);
	}
	if ($removed) {
		tomcat_restart();
	}
}

function tomcat_domain_suspend(&$data) {
	global $cfg;
	if ($data['serverside']['jsp'] == 'on') {
		if (tomcat_remove_host_conf($data)) {
			tomcat_restart();
		}
	}
}

function tomcat_domain_unsuspend(&$data) {
	global $cfg, $restarttomcat;
	if ($data['serverside']['jsp'] == 'on') {
		$file = $cfg['tomcatpath'].'/conf/server.xml';
		$tomcatconf = file_get_contents($file);

		$hostconf = tomcat_generate_host_conf($data);

		$tomcatarray = explode('<!-- VIRTUAL HOST INJECTION POINT -->', $tomcatconf);
		$tomcatconf = $tomcatarray[0]."<!-- VIRTUAL HOST INJECTION POINT -->\n".$hostconf."\n\n".trim($tomcatarray[1]);

		file_put_contents($file, $tomcatconf);
		tomcat_restart();
	}
}

function tomcat_domain_remove(&$data) {
	global $cfg, $restarttomcat;
	if ($data['serverside']['jsp'] == 'on') {
		if (tomcat_remove_host_conf($data)) {
			tomcat_restart();
		}
	}
}

function tomcat_monitor(&$data) {
	global $cfg;
	exec('ps aux | grep \''.$cfg['tomcatpath'].'/bin/\'', $result);
	if (preg_match('/[0-9]+/', $result[0], $match)) {
		$pid = $match[0];
		if (posix_kill($pid,0))
			$data['tomcat'] = 'up';
		else {
			$data['tomcat'] = 'down';
		}
	} else {
		$data['tomcat'] = 'down';
	}
	if ($data['tomcat'] == 'down') {
		if ($cfg['service_auto_start'] && $cfg['autostart']['tomcat']) {
			webcp_log(2,0,"monitor","service down: tomcat - attempting to start",0,$echo);
			tomcat_start();
			sleep(2);
			exec('ps aux | grep \''.$cfg['tomcatpath'].'/bin/\'', $result);
			if (preg_match('/[0-9]+/', $result[0], $match)) {
				$pid = $match[0];
				if (posix_kill($pid,0))
					$data['tomcat'] = 'up';
				else {
					$data['tomcat'] = 'down';
				}
			} else {
				$data['tomcat'] = 'down';
			}
		}
	}
	if ($data['tomcat'] == 'down') {
		webcp_log(1,0,"monitor","service down: tomcat",0,$echo);
	}
	return true;
}

function  tomcat_template(&$ret) {
	global $cfg;

	$template['title'] = 'Tomcat';
	$template['servicename'] = 'tomcat';
	$template['active'] = true;
	$template['file'][] = array('filename' => 'host');

	$ret[] = $template;

}

function tomcat_add_lang(&$data) {
	global $T;
	switch($data['lang']) {
		default:
			$T['ss']['jsp'] = 'JSP';
			$T['tomcat service'] = 'Tomcat';
			$T['Tomcat'] = 'Tomcat';
			$T['tomcat']['{PATH}']		= 'Path to the domain\'s document root.';
			$T['tomcat']['{ALIASES}']		= 'List of aliases for the main host and domain.';
			$T['tomcat']['{LOGPATH}']		= 'Path to the domain\'s log directory.';
			$T['tomcat']['{HOST.DOMAIN}']		= 'Host and domain name (eg. host.domain.tld).';
			$T['tomcat']['{TOMCATPATH}']		= 'Path to tomcat (eg. /usr/local/tomcat).';
			break;
	}
}

function tomcat_set_cfg(&$cfg) {
	$cfg['sslang'] .= ',jsp'; //TODO: this should be set using [server|web]:cfg:set
}

function tomcat_add_cfg(&$cfg) {
	$cfg['ss']['jsp'] 		= "\tJkMount /*.jsp ajp13\n";
	$cfg['tomcatpath'] = '/usr/local/tomcat';
	$cfg['spid']['tomcat'] = '/var/run/tomcat.pid';
	$cfg['init']['tomcat'] = $cfg['tomcatpath'].'/bin/catalina.sh';
	$cfg['autostart']['tomcat'] = true;
	$cfg['tomcat_tpl'] = true;
}

function tomcat_stop() {
	global $cfg;
	exec($cfg['init']['tomcat'].' stop');
}

function tomcat_start() {
	global $cfg;
	exec($cfg['init']['tomcat'].' start');
}

function tomcat_restart() {
	global $cfg;
	tomcat_stop();
	tomcat_start();
}
?>